package com.kh.first.controller;

import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kh.first.config.WxCpConfiguration;
import com.kh.first.pojo.ProductReportPojo;
import com.kh.first.pojo.SubordinatePojo;
import com.kh.first.pojo.common.AjaxJson;
import com.kh.first.pojo.common.Signature;
import com.kh.first.pojo.common.WxDepartment;
import com.kh.first.pojo.common.WxUser;
import com.kh.first.service.ProductReportService;
import com.kh.first.utils.UserUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.*;
import java.text.MessageFormat;
import java.util.*;

@RequestMapping("productReportController")
@Controller
public class ProductReportController {

    @Autowired
    ProductReportService productReportService;

    //        @RequestMapping(params = "createWxDepartment")
//    @ResponseBody//{"errcode":0,"errmsg":"ok","userid":"Wangqingqi","name":"王清旗","department":[129],"position":"","mobile":"13815096807","gender":"1","email":"","avatar":"http://wework.qpic.cn/bizmail/Cua67xjT1uXHibJIBThMdr8AF2tj9tobTqpJKJdWpP4tV0wkTOiaahBw/0","status":1,"isleader":0,"extattr":{"attrs":[]},"english_name":"201803787","telephone":"","enable":1,"hide_mobile":0,"order":[0],"external_profile":{"external_attr":[],"external_corp_name":""},"qr_code":"https://open.work.weixin.qq.com/wwopen/userQRCode?vcode=vc7a2f7b409b670237","alias":"201803787","is_leader_in_dept":[0],"address":"","thumb_avatar":"http://wework.qpic.cn/bizmail/Cua67xjT1uXHibJIBThMdr8AF2tj9tobTqpJKJdWpP4tV0wkTOiaahBw/100"}
    public AjaxJson<String> createWxDepartment() throws WxErrorException, IOException, ClassNotFoundException {
        AjaxJson<String> ajaxJson = new AjaxJson<>();
        WxCpService cpService = WxCpConfiguration.getCpService(1000008);
//            String userInfo  = cpService.get("https://qyapi.weixin.qq.com/cgi-bin/user/get", String.format("access_token=%s&userid=%s", cpService.getAccessToken(), "Wangqingqi"));
//        List<WxDepartMent> tree = getTree(1L);
//        ObjectOutputStream oos1 = new ObjectOutputStream(new FileOutputStream("d:/cache/department-duplicate"));
//        oos1.writeObject(tree);
//        oos1.flush();
//        oos1.close();
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:/cache/department"));
        List<WxDepartment> list = (List<WxDepartment>) ois.readObject();
        HashSet<Long> set = new HashSet<>();
        HashSet<String> setUserId = new HashSet<>();
        List<WxUser> orgUser = new ArrayList<>();
        List<WxUser> uniqueUser = new ArrayList<>();
//        String result = cpService.get("https://qyapi.weixin.qq.com/cgi-bin/user/list",
//                String.format("access_token=%s&department_id=%d&fetch_child=0", cpService.getAccessToken(), 129));
//        System.out.println();
//        wxUserDao.saveWxUserList(o.userlist);
//        for (WxDepartMent wxDepartMent : list) {
//            Long id = wxDepartMent.getId();
//            if (set.contains(id)) continue;
//            set.add(id);
////            list.add(wxDepartMent);
//            String result = cpService.get("https://qyapi.weixin.qq.com/cgi-bin/user/list",
//                    String.format("access_token=%s&department_id=%d&fetch_child=0", cpService.getAccessToken(), id));
//            AjaxJson<WxUser> userRes = objectMapper.readValue(result, new TypeReference<AjaxJson<WxUser>>() {
//            });
//            orgUser.addAll(userRes.userlist);
//        }
        for (WxUser wxUser : orgUser) {
            String userid = wxUser.getUserid();
            if (setUserId.contains(userid)) continue;

            setUserId.add(userid);
            uniqueUser.add(wxUser);
        }
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("d:/cache/user-duplicate"));
        oos.writeObject(orgUser);
        oos.flush();
        oos.close();
//        productReportService.saveWxUserList(uniqueUser);
//        productReportService.saveWxDepartMentList(list);
//        WxCpDepartmentService departmentService = cpService.getDepartmentService();

//        List<WxCpDepart> list = departmentService.list(1L);//131
//        WxCpDepart depart = new WxCpDepart();
//        depart.setParentId(1L);
//        depart.setName("计件工资部");
//        Long aLong = departmentService.create(depart);

        return ajaxJson;
    }

    @RequestMapping(params = "saveDepartment")
    @ResponseBody//保存部门
    public AjaxJson<String> saveDepartment() throws WxErrorException, IOException, ClassNotFoundException {
        AjaxJson<String> ajaxJson = new AjaxJson<>();
        List<WxDepartment> tree = getTree(1L);
        List<WxDepartment> list = new ArrayList<>();
        Set<Long> set = new HashSet<>();
        for (WxDepartment wxDepartMent : tree) {
            Long id = wxDepartMent.getId();
            if (set.contains(id)) continue;
            set.add(id);
            list.add(wxDepartMent);
        }
        String fileName = "d:/cache/department-0409-has-rename";
        saveObj(fileName, list);
//        List<WxDepartment> list = (List<WxDepartment>) readObj(fileName);

//        productReportService.saveWxDepartMentList(list);
        return ajaxJson;
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {

    }

    @RequestMapping(params = "saveUserInDb")
    @ResponseBody
    public AjaxJson<String> saveUserInDb() throws IOException, ClassNotFoundException {
        AjaxJson<String> ajaxJson = new AjaxJson<>();
        String fileNameUser = "d:/cache/userList";
        List<WxUser> uniqueUser = (List<WxUser>) readObj(fileNameUser);
        productReportService.saveWxUserList(uniqueUser);
        return ajaxJson;
    }

    @RequestMapping(params = "saveUser")
    @ResponseBody
    public AjaxJson<String> saveUser() throws IOException, ClassNotFoundException, WxErrorException {
        AjaxJson<String> ajaxJson = new AjaxJson<>();
        String fileName = "d:/cache/department";
        String fileNameUser = "d:/cache/userList";
        WxCpService cpService = WxCpConfiguration.getCpService(1000016);
        List<WxDepartment> departmentList = (List<WxDepartment>) readObj(fileName);
        HashSet<String> setUserId = new HashSet<>();
        List<WxUser> orgUser = new ArrayList<>();
        List<WxUser> uniqueUser = new ArrayList<>();
        for (WxDepartment wxDepartMent : departmentList) {
            Long id = wxDepartMent.getId();
            String result = cpService.get("https://qyapi.weixin.qq.com/cgi-bin/user/list",
                    String.format("access_token=%s&department_id=%d&fetch_child=0", cpService.getAccessToken(), id));
            AjaxJson<WxUser> userRes = objectMapper.readValue(result, new TypeReference<AjaxJson<WxUser>>() {
            });
            orgUser.addAll(userRes.userlist);
        }
        for (WxUser wxUser : orgUser) {
            String userid = wxUser.getUserid();
            if (setUserId.contains(userid)) continue;

            setUserId.add(userid);
            uniqueUser.add(wxUser);
        }
//        saveObj(fileNameUser,uniqueUser);
        System.out.println();
        return ajaxJson;
    }

    public static Object readObj(String fileName) throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));
        return ois.readObject();
    }

    public static void saveObj(String fileName, Object o) throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName));
        oos.writeObject(o);
        oos.flush();
        oos.close();
    }

    @RequestMapping(params = "createWxUser")
    @ResponseBody
    public AjaxJson<String> createWxUser() {
        AjaxJson<String> ajaxJson = new AjaxJson<>();

        return ajaxJson;
    }

    ObjectMapper objectMapper = new ObjectMapper();

    List<WxDepartment> getTree(Long id) throws WxErrorException, IOException {
        List<WxDepartment> list = new ArrayList<>();
        WxCpService cpService = WxCpConfiguration.getCpService(1000016);

        StringBuilder formatTemplate = new StringBuilder();
        formatTemplate.append("access_token=%s");
        if (id != null) {
            formatTemplate.append("&id=%d");
        }
        String format = String.format(formatTemplate.toString(), cpService.getAccessToken(), id);

        String json = cpService.get("https://qyapi.weixin.qq.com/cgi-bin/department/list", format);
        AjaxJson<WxDepartment> ajaxJson = objectMapper.readValue(json, new TypeReference<AjaxJson<WxDepartment>>() {
        });
        if (1 == ajaxJson.department.size()) return list;
        list.addAll(ajaxJson.department);
        List<WxDepartment> department = ajaxJson.department;
        for (int i = 0; i < department.size(); i++) {
            WxDepartment wxDepartMent = department.get(i);
            if (id == wxDepartMent.id) continue;
            list.addAll(getTree(wxDepartMent.id));
        }
        return list;
    }

    @RequestMapping(params = "getProductReportByIoUser")
    @ResponseBody
    public AjaxJson<ProductReportPojo> getProductReportByIoUser() {
        AjaxJson<ProductReportPojo> ajaxJson = new AjaxJson<>();
        List<ProductReportPojo> list =
                productReportService.getProductReportByIoUser(UserUtils.getUserPinYin() + ',');
        ajaxJson.list = list;
        return ajaxJson;
    }

    @RequestMapping(params = "getProductReportByCreateUserId")
    @ResponseBody
    public AjaxJson<ProductReportPojo> getProductReportByCreateUserId() {
        AjaxJson<ProductReportPojo> ajaxJson = new AjaxJson<>();
        List<ProductReportPojo> list =
                productReportService.getProductReportByCreateUserId(UserUtils.getUserPinYin());
        ajaxJson.list = list;
        return ajaxJson;
    }

    @RequestMapping(params = "adminUserJudge")
    @ResponseBody
    public AjaxJson<SubordinatePojo> adminUserJudge() {
        AjaxJson<SubordinatePojo> ajaxJson = new AjaxJson<>();
        SubordinatePojo subordinatePojo = productReportService.adminUserJudge(UserUtils.getUserPinYin());
        ajaxJson.data = subordinatePojo;
        if (null != subordinatePojo) {//有的话是2
            ajaxJson.code = 2;
        }
        return ajaxJson;
    }


    @RequestMapping(params = "getSignature")
    @ResponseBody
    public AjaxJson<String> getSignature(Signature signature) throws WxErrorException {
        AjaxJson<String> ajaxJson = new AjaxJson<>();
        Integer agentId = signature.getAgentId();
        WxCpService cpService = WxCpConfiguration.getCpService(agentId);
        String jsapiTicket = cpService.getJsapiTicket();
        String noncestr = signature.getNoncestr();
        Long timestamp = signature.getTimestamp();
        String url = signature.getUrl();
        String template = "jsapi_ticket={0}&" +
                "noncestr={1}&" +
                "timestamp={2,number,#}&" +
                "url={3}";
        String preSignature = MessageFormat.format(template, jsapiTicket, noncestr, timestamp, url);
        Digester digester = new Digester(DigestAlgorithm.SHA1);
        String digestHex = digester.digestHex(preSignature);
        ajaxJson.data = digestHex;
        return ajaxJson;
    }
/*

curl  -d 'dept=加工一科&productionLine=一号线&packageNumber=tx1件&schedulingNo=1&schedulingCategory=1' \
-X POST http://172.16.30.78/productReportController.do?createProductReport

 */
    //curl  -d 'dept=111&productionLine=222' -X POST http://localhost/productReportController.do?createProductReport

    @RequestMapping(params = "createProductReport")
    @ResponseBody//员工使用
    public AjaxJson<String> createProductReport(ProductReportPojo productReportPojo) {
        AjaxJson<String> ajaxJson = new AjaxJson<>();
        String userPinYin = UserUtils.getUserPinYin();
        String userName = UserUtils.getUserName();
        if(StringUtils.isBlank(userPinYin)){
            throw new IllegalArgumentException("不要通过这种方式访问");
        }
        productReportPojo.setCreateUserName(userPinYin);
        productReportPojo.setCreateUserWorkNo(userName);
        productReportPojo.setCreateTime(new Date());
        productReportService.saveProductReport(productReportPojo);
        return ajaxJson;
    }

    @RequestMapping(params = "getProductReportById")
    @ResponseBody
    public AjaxJson<ProductReportPojo> getProductReportById(Long id) {
        AjaxJson<ProductReportPojo> ajaxJson = new AjaxJson<>();
        ProductReportPojo productReportById = productReportService.getProductReportById(id);
        ajaxJson.data = productReportById;
        return ajaxJson;
    }

    @RequestMapping(params = "updateProductReportById")
    @ResponseBody
    public AjaxJson<String> updateProductReportById(ProductReportPojo productReportPojo) {
        AjaxJson<String> ajaxJson = new AjaxJson<>();
        productReportService.updateProductReportById(productReportPojo);
        return ajaxJson;
    }


    @RequestMapping(params = "getUserInfo")
    @ResponseBody
    public AjaxJson<String> getUserInfo(Integer agentId, String userId) throws WxErrorException, IOException {
        AjaxJson<String> ajaxJson = new AjaxJson<>();
        final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
        String result =
                wxCpService.get(
                        "https://qyapi.weixin.qq.com/cgi-bin/user/get",
                        String.format("access_token=%s&userid=%s",
                                wxCpService.getAccessToken(), userId)
                );
        WxUser wxUser = objectMapper.readValue(result, WxUser.class);
        ajaxJson.data = wxUser.getAlias();
        return ajaxJson;
    }
}
